package com.wusuowei.oauthserver.ucenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wusuowei.oauthserver.ucenter.mapper.UserMapper;
import com.wusuowei.oauthserver.ucenter.model.po.User;
import com.wusuowei.oauthserver.ucenter.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@RefreshScope
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserMapper userMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

//    @Value("${}")
//    String aa;

    @PostMapping("/getUser")
    public R getUser(Authentication authentication, HttpServletRequest httpServletRequest){

     //   System.err.println(aa);
        return R.ok().setData(authentication.getPrincipal());
    }

    @PostMapping("/register")
    public R register(@RequestBody User user) {
        // 新增或者更新
        String password = passwordEncoder.encode(user.getPassword());
        user.setPassword(password);
        user.setLoginDate(LocalDateTime.now());
        userMapper.insert(user);
        return R.ok();
    }
    /**
     * @description 检查用户名
     * @param username 用户名
     * @return {@link R }
     * @author LGY
     * @date 2023/03/24 21:09
     */
    @GetMapping("/check")
    public R countByUsername(@RequestParam String username) {
        long count = userMapper.selectCount(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        if(count!=0){
            return R.error("用户名已存在");
        }
        return R.ok();
    }
}
